<?php


namespace PKFrame\Lib\Cache;
defined('PATH_PK') or die();

use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\JSON;

class Local
{

    private static $instance;

    /**
     * @return Local
     */
    public static function getInstance(): Local
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        return self::$instance;
    }

    public function Read(string $name_file, string $name_dir = null)
    {
        $path = PATH_CACHE;
        is_null($name_dir) ?: $path .= ucfirst($name_dir) . DS;
        stristr($name_file, '.') ?: $name_file = ucfirst($name_file) . '.json';
        $content = fileHelper()->GetContentsByDisk($path . $name_file);
        if (JSON::Is($content)) {
            return json_decode($content, true);
        } else {
            return $content;
        }
    }

    public function ReadByConfig(string $name_file)
    {
        return $this->Read($name_file, 'Config');
    }

    public function ReadByData(string $name_file)
    {
        return $this->Read($name_file, 'Data');
    }

    public function Write(string $name_dir, string $name_file, $data)
    {
        fileHelper()->PutContents(PATH_CACHE . ucfirst($name_dir), $name_file, $data);
    }

    public function WriteByJSON(string $name_dir, string $name_file, array $data)
    {
        $this->Write($name_dir, $name_file . '.json', JSON::EnCode($data));
    }

    public function WriteByConfig(string $name_file, array $data)
    {
        $this->WriteByJSON('Config', $name_file, $data);
    }

    public function WriteByData(string $name_file, array $data)
    {
        $this->WriteByJSON('Data', $name_file, $data);
    }

    public function DelByData(string $name_file)
    {
        fileHelper()->UnLink(PATH_CACHE . 'Data' . DS . $name_file . '.json');
    }

}